package ups.Common;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Calendar;

import ups.Database.Database;

public class FileExport extends DataImporter {
	
	public static void main( String[] args ) {
		FileExport exp = new FileExport( args );
	}
	
	
	public FileExport( String[] args ) {
		super( args );
		Database db = new Database( DBHostName ,DBPort, DBName, DBUsername, DBPass);
		
		String query = "SELECT * from late ORDER BY date, scheduled_time;";
		
		StringBuffer string = new StringBuffer();
		
		try {
			ResultSet rs = db.execute( query );

			while( rs.next() ) {
			Calendar scheduledTime = Calendar.getInstance();
			scheduledTime.setTime( db.getTimeFormat().parse( rs.getString("scheduled_time")));

			Calendar actualTime = Calendar.getInstance();
			actualTime.setTime( db.getTimeFormat().parse( rs.getString("actual_time")));
			
			int actualTimeAsMinutes = 60 * actualTime.get( Calendar.HOUR ) + actualTime.get( Calendar.MINUTE );
			int scheduledAsMinutes = 60 * scheduledTime.get( Calendar.HOUR ) + scheduledTime.get( Calendar.MINUTE );
			int difference = Math.abs( actualTimeAsMinutes - scheduledAsMinutes );
			
			Calendar scheduledDate = Calendar.getInstance();
			scheduledDate.setTime( db.getDateFormat().parse( rs.getString("date")));
			scheduledDate.set( Calendar.SECOND, scheduledTime.get( Calendar.SECOND ));
			scheduledDate.set( Calendar.MINUTE, scheduledTime.get( Calendar.MINUTE ));
			scheduledDate.set( Calendar.HOUR, scheduledTime.get( Calendar.HOUR ));
			//Calendar.add
			
			string.append( rs.getString("route_id") + "\t" + db.getDateTimeFormat().format( scheduledDate.getTime() ) + "\t" + rs.getString("lateness") + "\n" );
		}
			
		FileWriter writer  = new FileWriter( new File( getArgumentForKey("--file")));
		writer.write( string.toString() );
		writer.flush();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
